package com.school.information.utils;

import cn.hutool.core.util.ObjectUtil;
import com.school.information.core.security.entity.SecurityUser;
import com.school.information.core.security.entity.WechatAppUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Set;

/**
 * 获取当前登录用户信息
 *
 * @author yuchuanchuan
 * @date 2020-12-01
 */
@Slf4j
public class UserUtil {

    /**
     * 返回当前登录用户信息
     *
     * @return
     */
    public static SecurityUser getUser() {
        try {
            SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return securityUser;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 返回当前用户 id
     *
     * @return
     */
    public static Long getUserId() {
        if (ObjectUtil.isEmpty(getUser())) {
            return null;
        }
        return getUser().getSysUser().getId();
    }

    /**
     * 返回当前用户 姓名
     *
     * @return
     */
    public static String getUserName() {
        if (StringUtils.isBlank(getUser().getSysUser().getRealName())) {
            return "";
        }
        return getUser().getSysUser().getRealName();
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId > 0 && 20230701 == userId.longValue();
    }

    /**
     * 获取权限标志信息
     *
     * @return
     */
    public static Set<String> getPerms() {
        return getUser().getPermissions();
    }

    /**
     * 获取用户角色信息
     */
    public static Set<String> getRoles() {
        return getUser().getRoles();
    }


    /**
     * 返回当前小程序登录用户信息
     *
     * @return
     */
    public static WechatAppUser getWechatUser() {
        try {
            WechatAppUser wechatAppUser = (WechatAppUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return wechatAppUser;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 返回当前小程序用户 id
     *
     * @return
     */
    public static Long getWechatUserId() {
        if (ObjectUtil.isEmpty(getWechatUser())) {
            return null;
        }
        return getWechatUser().getSysWechatUser().getId();
    }

    /**
     * 返回当前小程序用户 openid
     *
     * @return
     */
    public static String getWechatUserOpenid() {
        if (ObjectUtil.isEmpty(getWechatUser())) {
            return "";
        }
        return getWechatUser().getSysWechatUser().getOpenid();
    }

    /**
     * 返回当前小程序用户 session_key
     *
     * @return
     */
    public static String getWechatUserSessionKey() {
        if (ObjectUtil.isEmpty(getWechatUser())) {
            return "";
        }
        return getWechatUser().getSessionKey();
    }

}
